package com.assistant.codegen.modules.template.domain;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;
import lombok.AllArgsConstructor;
import org.springframework.util.StreamUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.function.BiFunction;

/**
 * 模版引擎
 */
@AllArgsConstructor
public enum TemplateEngine {

    freemarker((expressionStr, context) -> {
        final StringTemplateLoader templateLoader = new StringTemplateLoader();
        templateLoader.putTemplate("hello.ftl", expressionStr);

        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);

        configuration.setTemplateLoader(templateLoader);
        configuration.setDefaultEncoding("utf-8");

        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            configuration.getTemplate("hello.ftl").process(context, new OutputStreamWriter(byteArrayOutputStream));
        } catch (TemplateException | IOException e) {
            return "";
        }
        return StreamUtils.copyToString(byteArrayOutputStream, StandardCharsets.UTF_8);
    }),

    ;

    public BiFunction<String, Map<String, Object>, String> resolver;
}
